using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using PowerSearch.Core;
using PowerSearch.AppServices;
using Java.Net;
using Android.Graphics.Drawables;
using System.Net;
using Android.Graphics;
using System.Threading.Tasks;
using Android.Text;

namespace PowerSearch.ICS
{
	public class ResultAdapter : BaseAdapter
	{
		IList<Feed> _results;
		Activity _activity;
		string _provider;

		public ResultAdapter (Activity context, string provider, IList<Feed> result)
		{
			_activity = context;
			_results = result;
			_provider = provider;
		}

		public override int Count {
			get {
				return _results == null || _results.Count == 0 ? 0 : _results.Count;
			}
		}

		public override Java.Lang.Object GetItem (int position)
		{
			return null;
		}

		public override long GetItemId (int position)
		{
			return 1;
		}

		public override View GetView (int position, View convertView, ViewGroup parent)
		{
			var view = convertView ?? _activity.LayoutInflater.Inflate (Resource.Layout.Feed, parent, false);
			var txtTitle = view.FindViewById<TextView> (Resource.Id.txtTitle);
			var txtDescription = view.FindViewById<TextView> (Resource.Id.txtDescription);
			var imgDisplayUrl = view.FindViewById<ImageView> (Resource.Id.imgDisplayUrl);

			txtTitle.Text = _results [position].Title;
			txtDescription.Text = _results [position].Description;
			if (!string.IsNullOrEmpty(_results[position].DisplayUrl)) {
				Task.Factory.StartNew (() => LoadDisplayImage(imgDisplayUrl, _results[position].DisplayUrl));
			}

			if (!string.IsNullOrEmpty (_results[position].ClickUrl)) {
				view.Click += (object sender, EventArgs e) => {
					var webIntent = new Intent(_activity, typeof(ContentActivity));
					webIntent.PutExtra("ContentLink", _results[position].ClickUrl);
					webIntent.PutExtra("Provider", _provider);
					webIntent.PutExtra("Title", _results[position].Title);
					_activity.StartActivity(webIntent);
				};
			}

			return view;
		}

		private void LoadDisplayImage(ImageView imageView, string displayUrl)
		{
			var webClient = new WebClient ();
			var stream = webClient.DownloadData (new Uri(displayUrl));
			Bitmap bm = BitmapFactory.DecodeByteArray (stream, 0, stream.Length);

			_activity.RunOnUiThread (() => {
				imageView.SetImageBitmap(bm);
			});
		}
	}
}

